// https://leetcode.cn/problems/degree-of-an-array/
// Created by ade on 2022/8/12.
//
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int findShortestSubArray(vector<int> &nums) {
        unordered_map<int, int> m = {};
        unordered_map<int, vector<int>> pos = {};
        int maxN = 0;
        int minN = INT_MAX;
        for (int i = 0; i < nums.size(); i++) {
            m[nums[i]]++;
            if (pos.find(nums[i]) == pos.end()) {
                pos[nums[i]] = {i, i};
            } else {
                pos[nums[i]][1] = i;
            }
            if (maxN < m[nums[i]]) {
                maxN = max(maxN, m[nums[i]]);
                minN = i - pos[nums[i]][0] + 1;
            } else if (maxN == m[nums[i]]) {
                minN = min(minN, i - pos[nums[i]][0] + 1);
            }
        }
        return minN;
    }
};

int main() {
    Solution so;
    vector<int> nums = {1, 2, 2, 3, 1, 4, 2};
    auto res = so.findShortestSubArray(nums);
    cout << res << endl;
    return 0;
}